﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.IO;
using TomanuExtensions;

namespace AmiEmuLib.Configuration.AmigaEventsConfig
{
    /// <summary>
    /// List of events for devices.
    /// </summary>
    [DebuggerDisplay("Count = {Count}")]
    public static class AmigaEventsList
    {
        /// <summary>
        /// List of inputs events
        /// </summary>
        private static List<AmigaEvents> m_events = new List<AmigaEvents>();

        /// <summary>
        /// Static constructor.
        /// </summary>
        static AmigaEventsList()
        {
            using (Stream stream = StreamExtensions.FromResource(typeof(AmigaEventsList), 
                "AmigaEventsList.xml"))
            {
                XmlReaderExtensions.ReadXml(stream, (reader) =>
                {
                    reader.ReadStartElement(typeof(AmigaEventsList).Name);

                    while (reader.IsStartElement())
                        m_events.Add(new AmigaEvents(reader));

                    reader.ReadEndElement();
                });
            }
        }

        /// <summary>
        /// List of inputs events
        /// </summary>
        public static IEnumerable<AmigaEvents> Events
        {
            get
            {
                return m_events;
            }
        }

        /// <summary>
        /// Save events list to xml. Only for development.
        /// </summary>
        public static void SaveToXml()
        {
            XmlWriterExtensions.WriteXml("AmigaEventsList.xml", (writer) =>
            {
                writer.WriteStartElement(typeof(AmigaEventsList).Name);

                foreach (var evs in m_events) 
                    evs.WriteXml(writer, true);

                writer.WriteEndElement();
            });
        }

        /// <summary>
        /// Get event from name.
        /// </summary>
        /// <param name="a_name"></param>
        /// <returns></returns>
        public static AmigaEvent GetEvent(string a_name)
        {
            return Events.SelectMany(evs => evs.Events).FirstOrDefault(av => av.Name == a_name);
        }

        /// <summary>
        /// Get events for device.
        /// </summary>
        /// <param name="a_device"></param>
        /// <returns></returns>
        public static AmigaEvents GetEvents(AmigaDeviceType a_device)
        {
            foreach (var evs in m_events)
            {
                if (evs.DeviceType == a_device)
                    return evs;
            }

            return null;
        }
    }
}
